package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.UnicodeUtil;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 迈远
 */
public class SmsApiMYJK extends GateWayHttpAbstract
{

    public SmsApiMYJK(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        String t = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid", paramsMaps.get("userid"));
        params.put("account", paramsMaps.get("account"));
        params.put("password", paramsMaps.get("password"));
        params.put("mobile", mt.getPhone());
        try {
            params.put("content", URLEncoder.encode(mt.getSmsContent(),"UTF-8"));
            params.put("sendTime",URLEncoder.encode(t,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("提交网关短信内容utf-8编码错误，网关:{}, 短信内容:{}", this.gateWayID, mt.getSmsContent());
        }
        params.put("action", "send");
        params.put("extno", paramsMaps.get("extno"));
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/sms.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        List<SMSSRMessage> resultList = Lists.newArrayList();

        SMSSRMessage message = initGatewayResultMessage(result, mt, "returnstatus");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        Document doucResult;
        try {
            doucResult = DocumentHelper.parseText(result);
            Element root = doucResult.getRootElement();
            if(StringUtils.equals(message.getResult(), "F10199")) {
                resultCode = root.element("returnstatus").getStringValue();
                resultMessage = root.element("message").getStringValue();
                if(StringUtils.equals(resultCode, "Success")) {
                    taskid = root.element("taskID").getStringValue();
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "Success");
                resultList.add(message);
            }
        }catch (DocumentException e) {
            e.printStackTrace();
            logger.info("提交网关结果解析错误，网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                if (StringUtils.contains(text,"statusbox")) {
                    logger.info("{}网关推送状态报告:{}", gateWayID, text);
                    List<Element> itemElements = root.elements("statusbox");
                    for (Element data : itemElements) {
                        SMSRTMessage smsRtMessage = initSmsRtMessage(data.element("taskid").getStringValue(), data.element("mobile").getStringValue(), data.element("mobile").getStringValue(),
                                data.element("status").getStringValue(), "10");
                        rtList.add(smsRtMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                if (StringUtils.contains(text,"callbox")) {
                    logger.info("{}网关推送用户上行:{}", gateWayID, text);
                    List<Element> itemElements = root.elements("callbox");
                    for (Element data : itemElements) {
                        SMSMOMessage sMSMOMessage = new SMSMOMessage();
                        sMSMOMessage.setGateWayID(gateWayID);
                        sMSMOMessage.setMsgContent(UnicodeUtil.decode(data.element("content").getStringValue()));
                        sMSMOMessage.setMsgid(root.element("taskid").getStringValue());
                        sMSMOMessage.setPhone(data.element("mobile").getStringValue());
                        sMSMOMessage.setSenttime(data.element("receivetime").getStringValue());
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                        sMSMOMessage.setUuid(UUID.randomUUID().toString());
                        moList.add(sMSMOMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        Map<String,String> params = Maps.newHashMap();
        params.put("userid",paramsMaps.get("userid"));
        params.put("account",paramsMaps.get("account"));
        params.put("password",paramsMaps.get("password"));
        params.put("statusNum",paramsMaps.get("statusNum"));
        params.put("action","query");
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/statusApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
//        logger.info("网关：{}主动获取订单状态结果:{}", gateWayID, result);
        if (result.contains("statusbox"))
            return result;
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        Map<String,String> params = Maps.newHashMap();
        params.put("userid",paramsMaps.get("userid"));
        params.put("account",paramsMaps.get("account"));
        params.put("password",paramsMaps.get("password"));
        params.put("action","query");
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/callApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        if (result.contains("callbox"))
            return result;
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid",paramsMaps.get("userid"));
        params.put("account",paramsMaps.get("account"));
        params.put("password",paramsMaps.get("password"));
        params.put("action","overage");
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/sms.aspx" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        Document  docuResult;
        try{
            docuResult  = DocumentHelper.parseText(result);
            Element root = docuResult.getRootElement();
            root.getStringValue();
            if (StringUtils.equals("Sucess",root.element("returnstatus").getStringValue())) {
                return "余额：" + root.element("overage").getStringValue() + ",点数：" + root.element("sendTotal").getStringValue();
            }
        }catch (DocumentException e){
            e.printStackTrace();
            logger.error("余额查询xml解析失败，网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
            return "余额查询解析错误";
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"userid\":\"2702\",\"account\":\"yuanheng\",\"password\":\"yuanheng\",\"apiUrl\":\"http://1.82.233.146:6068\",\"extno\":\"\",\"statusNum\":\"4000\",\"deliverSecTime\":\"600\"}";
//        String params = "{\"userid\":\"258\",\"account\":\"hzfs-wd\",\"password\":\"hzfs-wd123\",\"apiUrl\":\"http://qxsmst.ronglaids.net\",\"extno\":\"\",\"statusNum\":\"4000\",\"deliverSecTime\":\"60\"}";

        SmsApiMYJK api = new SmsApiMYJK("ZY",params);
        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18368493887");
        message.setId("test123456");
        message.setSmsContent("【等都科技】你的短信验证码是432446");
//        api.doSend(message);
//        api.queryDeliver("");
        api.queryReport("");
        String reportText = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><returnsms> <statusbox> <mobile>18268846802</mobile> <taskid>2082039</taskid> <status>10</status> <receivetime>2018-03-23 14:46:09</receivetime> <errorcode><![CDATA[DELIVRD]]></errorcode> <extno><![CDATA[2728]]></extno> </statusbox> </returnsms>";
    }
    
}